package com.tanhua.server.service;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Option;
import com.tanhua.domain.mongo.Question;
import com.tanhua.domain.mongo.Questionnarie;
import com.tanhua.domain.mongo.Report;
import com.tanhua.domain.vo.Dimensions;
import com.tanhua.domain.vo.testSoul.QuestionListVo;
import com.tanhua.domain.vo.ReportVo;
import com.tanhua.domain.vo.testSoul.OptionsVo;
import com.tanhua.domain.vo.testSoul.QuestionsVo;
import com.tanhua.domain.vo.testSoul.SimilarYouVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.MongoQuestionApi;
import com.tanhua.dubbo.api.mongo.OptionApi;
import com.tanhua.dubbo.api.mongo.QuestionnarieApi;
import com.tanhua.dubbo.api.mongo.ReportApi;
import com.tanhua.server.controller.TestSoulController;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TestSoulService {

    @Reference
    private QuestionnarieApi questionnarieApi;

    @Reference
    private MongoQuestionApi mongoQuestionApi;

    @Reference
    private OptionApi optionApi;

    @Reference
    private ReportApi reportApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private TestSoulController testSoulController;

    //【项目实战】问题列表业务
    public ResponseEntity<Object> showQuestion() throws InvocationTargetException, IllegalAccessException {
        List<Questionnarie> list = questionnarieApi.findAll(); //获取三套题
        List<QuestionListVo> vos = new ArrayList<>();  //返回值封装类 一
        if (list != null) {
            for (Questionnarie questionnarie : list) {
                ObjectId qid = questionnarie.getId(); //等级id
                List<Question> qList = mongoQuestionApi.findByQid(qid); //获得所有问题
                List<QuestionsVo> questions = new ArrayList<>();  //试题封装 二
                if (qList != null) {
                    for (Question question : qList) {
                        ObjectId qqId = question.getId(); //每道题的id
                        List<Option> oList = optionApi.findByQid(qqId); //选项列表
                        List<OptionsVo> options = new ArrayList<>();  //选项封装 三
                        if (oList != null) {
                            for (Option option : oList) {
                                OptionsVo ovo = new OptionsVo(option.getId().toString(),option.getContext());
                                options.add(ovo);
                            }
                        }
                        QuestionsVo qvo = new QuestionsVo(); //二
                        qvo.setId(question.getId().toString());
                        qvo.setQuestion(question.getText());
                        qvo.setOptions(options);  //三
                        questions.add(qvo);
                    }
                }
                QuestionListVo vo = new QuestionListVo();  //一
                BeanUtils.copyProperties(vo, questionnarie);
                vo.setQuestions(questions);
                vo.setId(questionnarie.getId().toString());
                //从redis中获取key，用于解锁问卷
                String key1 = "testSoul_q1_user_" + UserHolder.getUserId();
                String key2 = "testSoul_q2_user_" + UserHolder.getUserId();
                String key3 = "testSoul_q3_user_" + UserHolder.getUserId();
                List<Report> reports = reportApi.findByUser(UserHolder.getUserId());

                if (reports.size() == 0){
                    vo.setReportId(null);
                }else{
                    setReportId(questionnarie,vo,reports);
                }

                if (questionnarie.getLevel().equals("初级")) {
                    vo.setStar(2);
                    vo.setIsLock(0);
                    vo.setName("初级测试题");
                } else if (questionnarie.getLevel().equals("中级")) {
                    vo.setStar(3);
                    vo.setIsLock(1);
                    String s1 = redisTemplate.opsForValue().get(key1);
                    String s3 = redisTemplate.opsForValue().get(key3);
                    if (s1 != null || s3 != null) {
                        vo.setIsLock(0);
                    }
                    vo.setName("中级测试题");
                } else {
                    vo.setStar(5);
                    vo.setIsLock(1);
                    vo.setName("高级测试题");
                    String s2 = redisTemplate.opsForValue().get(key2);
                    String s3 = redisTemplate.opsForValue().get(key3);
                    if (s2 != null || s3 != null) {
                        vo.setIsLock(0);
                    }
                }

                vos.add(vo);
            }
        }
        return ResponseEntity.ok(vos);
    }

    //测灵魂-提交问卷业务
    public ResponseEntity<Object> commit(List<Map<String,String>> list) {
        Report report = null;
        ReportVo vo = new ReportVo();
        Integer count = 0;
        ObjectId rid = null;
        //获取请求传入的问题及答案【复数】
        if (list != null){
            //根据问题编号查询问卷等级，返回给report
            Question q = mongoQuestionApi.findById(new ObjectId(list.get(0).get("questionId")));
            Questionnarie questionnarie = questionnarieApi.findById(q.getQuestionnaireId());
                report = new Report();
            for (Map<String, String> answers: list) {
                String questionId = answers.get("questionId");
                String optionId = answers.get("optionId");
                Option option = optionApi.findForScore(optionId,questionId);
                if(option != null){
                    Integer weight = option.getWeight();
                    count += weight;
                }
            }
            //补齐report属性
            report.setUserId(UserHolder.getUserId());
            report.setQId(questionnarie.getId());
            report.setScore(count);
            report.setUpdated(System.currentTimeMillis());
            //设置维度值键值对，用于设置四边图
            HashMap<String, String> dimensions = new HashMap<>();
            //根据分数设置报告封面和文本,设置维度值键值对，用于设置四边图
            if (count < 21 && count >= 0){
                report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/owl.png");
                report.setConclusion("猫头鹰：他们的共同特质为重计划、条理、细节精准。在行为上，表现出喜欢理性思考与分析、较重视制度、结构、规范。他们注重执行游戏规则、循规蹈矩、巨细靡遗、重视品质、敬业负责。");
                dimensions.put("外向", "80%");
                dimensions.put("判断", "70%");
                dimensions.put("抽象", "90%");
                dimensions.put("理性", "60%");
                report.setDimension(dimensions);
            }else if(count >= 21 && count < 40){
                report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/rabbit.png");
                report.setConclusion("白兔型：平易近人、敦厚可靠、避免冲突与不具批判性。在行为上，表现出不慌不忙、冷静自持的态度。他们注重稳定与中长程规划，现实生活中，常会反思自省并以和谐为中心，即使面对困境，亦能泰然自若，从容应付。");
                dimensions.put("外向", "90%");
                dimensions.put("判断", "80%");
                dimensions.put("抽象", "70%");
                dimensions.put("理性", "60%");
                report.setDimension(dimensions);
            }else if(count >= 41 && count < 55){
                report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/fox.png");
                report.setConclusion("狐狸型 ：人际关系能力极强，擅长以口语表达感受而引起共鸣，很会激励并带动气氛。他们喜欢跟别人互动，重视群体的归属感，基本上是比较「人际导向」。由于他们富同理心并乐于分享，具有很好的亲和力，在服务业、销售业、传播业及公共关系等领域中，狐狸型的领导者都有很杰出的表现。");
                dimensions.put("外向", "60%");
                dimensions.put("判断", "70%");
                dimensions.put("抽象", "80%");
                dimensions.put("理性", "90%");
                report.setDimension(dimensions);
            }else{
                report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/lion.png");
                report.setConclusion("狮子型：性格为充满自信、竞争心强、主动且企图心强烈，是个有决断力的领导者。一般而言，狮子型的人胸怀大志，勇于冒险，看问题能够直指核心，并对目标全力以赴。\n" +
                        "他们在领导风格及决策上，强调权威与果断，擅长危机处理，此种性格最适合开创性与改革性的工作。");
                dimensions.put("外向", "90%");
                dimensions.put("判断", "60%");
                dimensions.put("抽象", "70%");
                dimensions.put("理性", "80%");
                report.setDimension(dimensions);
            }

            //将封装好的report数据上传到mongoDB
            Report save = reportApi.save(report);


            //如果用户成功递交问卷，在redis中生成相应的key，用于问卷列表解锁
            String key = null;

            String level = questionnarie.getLevel();
            switch (level){
                case "初级":
                    key = "testSoul_q1_user_" + UserHolder.getUserId();
                    break;
                case "中级":
                    key = "testSoul_q2_user_" + UserHolder.getUserId();
                    break;
                case "高级":
                    key = "testSoul_q3_user_" + UserHolder.getUserId();
                    break;
            }
            redisTemplate.opsForValue().set(key,"1");

            rid = save.getId();

        }
        return ResponseEntity.ok(rid.toString());
    }

    //测灵魂-查看结果
    public ResponseEntity<Object> showReport(String rid) throws InvocationTargetException, IllegalAccessException {
        ObjectId reportId = new ObjectId(rid);
        Report report = reportApi.findById(reportId);
        ReportVo vo = new ReportVo();
        vo.setConclusion(report.getConclusion());

        //从report中获取dimension包装
        Map<String, String> dimension = report.getDimension();
        Dimensions d1 = new Dimensions("外向",dimension.get("外向"));
        Dimensions d2 = new Dimensions("判断",dimension.get("判断"));
        Dimensions d3 = new Dimensions("抽象",dimension.get("抽象"));
        Dimensions d4 = new Dimensions("理性",dimension.get("理性"));
        Dimensions[] dimensions = {d1, d2, d3, d4};

        BeanUtils.copyProperties(vo,report);
        List<Report> list = reportApi.findSimilar(reportId);
        List<SimilarYouVo> similarList = new ArrayList<>();
        if(list != null){
            for (Report r : list) {
                if (UserHolder.getUserId().equals(r.getUserId())){
                    continue;
                }
                UserInfo userInfo = userInfoApi.findById(r.getUserId());
                SimilarYouVo similarYouVo = new SimilarYouVo(userInfo.getId().intValue(),userInfo.getAvatar());
                similarList.add(similarYouVo);
            }
        }

        vo.setDimensions(dimensions);

        vo.setSimilarYou(similarList);

        //保留新添加的的report，删除旧的report
        reportApi.removeOldReport(UserHolder.getUserId());

        return ResponseEntity.ok(vo);

    }

    //查询功能
    public void setReportId(Questionnarie questionnarie, QuestionListVo vo, List<Report> reports) {
        if (reports != null) {
            for (Report report : reports) {
                if (questionnarie != null && questionnarie.getLevel().equals("初级")) {
                    vo.setReportId(reportApi.findByQnId("6118815ace2c1224a06916ab", UserHolder.getUserId()));
                    int a = 10;
                }else if (questionnarie != null && questionnarie.getLevel().equals("中级")) {
                    vo.setReportId(reportApi.findByQnId("6118815ace2c1224a06916ad", UserHolder.getUserId()));
                    int b = 10;
                }else if (questionnarie != null && questionnarie.getLevel().equals("高级")) {
                    vo.setReportId(reportApi.findByQnId("6118815ace2c1224a06916ae", UserHolder.getUserId()));
                    int c = 10;
                }else{
                    vo.setReportId(null);
                    int d = 10;
                }
            }
        }else{
            vo.setReportId(null);
        }
    }
}
